import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

export default function Ai() {
  const navigate = useNavigate();
       const [messages, setMessages] = useState([
    { role: 'ai', content: '你好！我是AI助手，有什么可以帮你？' }
  ]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [selectedModel, setSelectedModel] = useState('ollama'); // 默认使用 Ollama
  const [systemPrompt, setSystemPrompt] = useState('你是一个有用的AI助手。');
  const [temperature, setTemperature] = useState(0.7);
  const [maxTokens, setMaxTokens] = useState(2048);
  const [config, setConfig] = useState(null);
  const [ollamaStatus, setOllamaStatus] = useState(null);

  const [currentSessionId, setCurrentSessionId] = useState(null);
  const [sessions, setSessions] = useState([]);
  const [showSessions, setShowSessions] = useState(false);
  const [sessionsLoading, setSessionsLoading] = useState(false);
  const [isRecording, setIsRecording] = useState(false);
  const [recognition, setRecognition] = useState(null);
  const [voiceLanguage, setVoiceLanguage] = useState('zh-CN');
  const [voiceStatus, setVoiceStatus] = useState('未初始化');
  const [recordingTimeout, setRecordingTimeout] = useState(null);
  const [retryCount, setRetryCount] = useState(0);
  const [selectedImage, setSelectedImage] = useState(null);
  const [imagePreview, setImagePreview] = useState(null);
  const [chatStats, setChatStats] = useState(null);
  const [showStats, setShowStats] = useState(false);
  const [detectedLanguage, setDetectedLanguage] = useState(null);
  const fileInputRef = useRef(null);
  const chatRef = useRef(null);

  // 获取配置信息
  useEffect(() => {
    fetchConfig();
    checkOllamaStatus();
    loadSessions();
    loadChatStats();
    initSpeechRecognition();
  }, []);

  // 初始化语音识别
  const initSpeechRecognition = () => {
    if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
      const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
      const recognitionInstance = new SpeechRecognition();
      
      recognitionInstance.continuous = false;
      recognitionInstance.interimResults = true; // 启用实时结果
      recognitionInstance.maxAlternatives = 1;
      recognitionInstance.lang = voiceLanguage;
      
      recognitionInstance.onstart = () => {
        setIsRecording(true);
        setVoiceStatus('录音中');
        console.log('语音识别开始');
        
        // 设置超时，10秒后自动停止
        const timeout = setTimeout(() => {
          if (recognitionInstance) {
            recognitionInstance.stop();
            setVoiceStatus('超时停止');
            console.log('语音识别超时停止');
          }
        }, 10000);
        setRecordingTimeout(timeout);
      };
      
      recognitionInstance.onresult = (event) => {
        let finalTranscript = '';
        let interimTranscript = '';
        
        for (let i = event.resultIndex; i < event.results.length; i++) {
          const transcript = event.results[i][0].transcript;
          if (event.results[i].isFinal) {
            finalTranscript += transcript;
          } else {
            interimTranscript += transcript;
          }
        }
        
        // 如果有最终结果，使用最终结果
        if (finalTranscript) {
          setInput(finalTranscript);
          setIsRecording(false);
          setVoiceStatus('识别成功');
          console.log('语音识别最终结果:', finalTranscript);
        } else if (interimTranscript) {
          // 显示临时结果
          setInput(interimTranscript);
          setVoiceStatus('识别中...');
          console.log('语音识别临时结果:', interimTranscript);
        }
      };
      
      recognitionInstance.onerror = (event) => {
        console.error('语音识别错误:', event.error);
        setIsRecording(false);
        setVoiceStatus(`错误: ${event.error}`);
        
        let errorMessage = '语音识别出现错误';
        switch (event.error) {
          case 'not-allowed':
            errorMessage = '请允许浏览器使用麦克风权限，并刷新页面重试';
            break;
          case 'no-speech':
            errorMessage = '没有检测到语音，请说话或检查麦克风\n\n建议：\n1. 确保麦克风正常工作\n2. 说话声音要清晰\n3. 避免环境噪音\n4. 尝试重新点击语音按钮';
            break;
          case 'audio-capture':
            errorMessage = '无法访问麦克风，请检查设备连接';
            break;
          case 'network':
            errorMessage = '网络错误，请检查网络连接\n\n建议：\n1. 检查网络连接是否正常\n2. 尝试刷新页面\n3. 检查防火墙设置\n4. 尝试使用其他浏览器';
            // 网络错误时自动重试
            if (retryCount < 3) {
              setTimeout(() => {
                console.log(`🔄 网络错误，第${retryCount + 1}次重试...`);
                setRetryCount(prev => prev + 1);
                setVoiceStatus('重试中...');
                recognitionInstance.start();
              }, 2000);
            } else {
              setRetryCount(0);
              setVoiceStatus('网络错误，重试失败');
            }
            break;
          case 'service-not-allowed':
            errorMessage = '语音识别服务不可用，请稍后重试';
            break;
          case 'bad-grammar':
            errorMessage = '语音识别语法错误';
            break;
          case 'language-not-supported':
            errorMessage = '不支持当前选择的语言';
            break;
          default:
            errorMessage = `语音识别错误: ${event.error}`;
        }
        
        // 对于 no-speech 和 network 错误，不显示弹窗，只在状态栏显示
        if (event.error !== 'no-speech' && event.error !== 'network') {
          alert(errorMessage);
        }
        console.log('详细错误信息:', event);
      };
      
      recognitionInstance.onend = () => {
        setIsRecording(false);
        setVoiceStatus('就绪');
        console.log('语音识别结束');
        
        // 重置重试计数
        setRetryCount(0);
        
        // 清除超时定时器
        if (recordingTimeout) {
          clearTimeout(recordingTimeout);
          setRecordingTimeout(null);
        }
      };
      
      setRecognition(recognitionInstance);
      setVoiceStatus('已初始化');
      console.log('语音识别初始化成功');
    } else {
      console.warn('浏览器不支持语音识别功能');
      setVoiceStatus('不支持');
    }
  };

  const fetchConfig = async () => {
    try {
      const response = await fetch('/zjx/config');
      const data = await response.json();
      setConfig(data);
      if (data.defaultModel) {
        setSelectedModel(data.defaultModel);
      }
    } catch (error) {
      console.error('获取配置失败:', error);
    }
  };

  const checkOllamaStatus = async () => {
    console.log('🔍 正在检查 Ollama 状态...');
    try {
      const response = await fetch('/zjx/ollama-status');
      console.log('📡 Ollama 请求响应:', response.status, response.url);
      const data = await response.json();
      console.log('📊 Ollama 状态数据:', data);
      setOllamaStatus(data);
    } catch (error) {
      console.error('❌ 检查 Ollama 状态失败:', error);
      setOllamaStatus({ success: false, error: '连接失败' });
    }
  };



  // 加载会话列表
  const loadSessions = async () => {
    try {
      setSessionsLoading(true);
      const response = await fetch('/zjx/sessions?userId=anonymous');
      const data = await response.json();
      if (data.success) {
        setSessions(data.sessions);
        console.log('会话列表已更新，共', data.sessions.length, '个会话');
        
        // 打印每个会话的消息数量，用于调试
        data.sessions.forEach(session => {
          console.log(`会话 "${session.title}": ${session.messageCount} 条消息`);
        });
        
        // 同时更新统计信息
        await loadChatStats();
      } else {
        console.error('加载会话列表失败:', data.error);
      }
    } catch (error) {
      console.error('加载会话列表失败:', error);
    } finally {
      setSessionsLoading(false);
    }
  };

  // 创建新会话
  const createNewSession = async () => {
    try {
      const response = await fetch('/zjx/sessions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: 'anonymous',
          title: '新对话'
        })
      });
      const data = await response.json();
      if (data.success) {
        setCurrentSessionId(data.sessionId);
        setMessages([{ role: 'ai', content: '你好！我是AI助手，有什么可以帮你？' }]);
        // 创建新会话时更新会话列表和统计信息
        await Promise.all([loadSessions(), loadChatStats()]);
      }
    } catch (error) {
      console.error('创建新会话失败:', error);
    }
  };

  // 加载特定会话
  const loadSession = async (sessionId) => {
    try {
      const response = await fetch(`/zjx/sessions/${sessionId}`);
      const data = await response.json();
      if (data.success) {
        setCurrentSessionId(sessionId);
        setMessages(data.session.messages);
        setSelectedModel(data.session.selectedModel || 'ollama');
        setSystemPrompt(data.session.systemPrompt || '你是一个有用的AI助手。');
        setTemperature(data.session.temperature || 0.7);
        setMaxTokens(data.session.maxTokens || 2048);
        setShowSessions(false);
        
        // 清除当前图片预览
        setSelectedImage(null);
        setImagePreview(null);
        if (fileInputRef.current) {
          fileInputRef.current.value = '';
        }
      }
    } catch (error) {
      console.error('加载会话失败:', error);
    }
  };

  // 删除会话
  const deleteSession = async (sessionId) => {
    try {
      const response = await fetch(`/zjx/sessions/${sessionId}`, {
        method: 'DELETE'
      });
      const data = await response.json();
      if (data.success) {
        if (currentSessionId === sessionId) {
          setCurrentSessionId(null);
          setMessages([{ role: 'ai', content: '你好！我是AI助手，有什么可以帮你？' }]);
        }
        // 删除会话时只更新会话列表，不更新统计信息（最近7天统计基于创建时间）
        await loadSessions();
      }
    } catch (error) {
      console.error('删除会话失败:', error);
    }
  };

  // 滚动到底部
  const scrollToBottom = () => {
    if (chatRef.current) {
      chatRef.current.scrollTop = chatRef.current.scrollHeight;
    }
  };



  // 发送消息
  // 打字机效果函数
  const typewriterEffect = (text, messageIndex) => {
    const lines = text.split('\n');
    let currentLineIndex = 0;
    let currentCharIndex = 0;
    let displayText = '';
    
    const typeNextChar = () => {
      if (currentLineIndex < lines.length) {
        if (currentCharIndex < lines[currentLineIndex].length) {
          displayText += lines[currentLineIndex][currentCharIndex];
          currentCharIndex++;
        } else {
          displayText += '\n';
          currentLineIndex++;
          currentCharIndex = 0;
        }
        
        setMessages(msgs => {
          const newMsgs = [...msgs];
          newMsgs[messageIndex] = { ...newMsgs[messageIndex], content: displayText };
          return newMsgs;
        });
        
        // 自动滚动到底部
        setTimeout(scrollToBottom, 10);
        
        // 修复递归条件：只有当还有内容需要显示时才继续
        if (currentLineIndex < lines.length) {
          setTimeout(typeNextChar, 15); // 每15毫秒显示一个字符，更快的速度
        } else {
          // 打字机效果完成后，再次更新会话列表以确保数据同步
          setTimeout(() => {
            loadSessions();
          }, 500);
        }
      }
    };
    
    typeNextChar();
  };

  const sendMessage = async () => {
    const text = input.trim();
    
    if (!text && !selectedImage) return;
    if (loading) return;

    // 如果没有当前会话，自动创建一个新会话
    let sessionId = currentSessionId;
    if (!sessionId) {
      try {
        const createResponse = await fetch('/zjx/sessions', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            userId: 'anonymous',
            title: text.substring(0, 30) + (text.length > 30 ? '...' : '')
          })
        });
        const createData = await createResponse.json();
        if (createData.success) {
          sessionId = createData.sessionId;
          setCurrentSessionId(sessionId);
        }
      } catch (error) {
        console.error('自动创建会话失败:', error);
      }
    }

    // 添加用户消息到聊天记录
    const userMessage = {
      role: 'user',
      content: text || (selectedImage ? '请识别这张图片' : ''),
      image: selectedImage
    };
    setMessages(msgs => [...msgs, userMessage]);
    
    setInput('');
    setLoading(true);

    try {
      const requestData = {
        message: text || (selectedImage ? '请识别这张图片' : ''),
        image: selectedImage,
        sessionId: sessionId,
        model: selectedModel,
        systemPrompt: systemPrompt,
        temperature: temperature,
        maxTokens: maxTokens
      };

      const res = await fetch('/zjx/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(requestData)
      });
      const data = await res.json();
      
      // 显示检测到的语言信息
      if (data.detectedLanguage) {
        setDetectedLanguage(data.detectedLanguage);
        console.log('检测到的语言:', data.detectedLanguage);
      }
      
      if (data.success) {
        // AI 响应成功
        const modelInfo = data.model === 'ollama' ? ` (${data.modelName || 'Ollama'})` : ' (Coze)';
        let responseContent = data.response || 'AI响应成功';
        
        // 如果是coze，显示详细的调试信息
        if (data.model === 'coze') {
          console.log('Coze 响应详情:', {
            response: data.response,
            responseType: data.responseType,
            usage: data.usage,
            rawResponse: data.rawResponse
          });
          
          // 如果响应内容包含错误信息，显示调试数据
          if (responseContent.includes('响应格式异常') || responseContent.includes('无法解析')) {
            responseContent = `调试信息:\n响应类型: ${data.responseType}\nAI回复: ${data.response}\n\n原始数据: ${JSON.stringify(data.rawResponse, null, 2)}`;
          }
        }
        
        // 更新用户消息，添加语言检测信息
        if (data.detectedLanguage) {
          setMessages(msgs => {
            const updatedMsgs = [...msgs];
            const lastUserMsgIndex = updatedMsgs.length - 1;
            if (updatedMsgs[lastUserMsgIndex] && updatedMsgs[lastUserMsgIndex].role === 'user') {
              updatedMsgs[lastUserMsgIndex] = {
                ...updatedMsgs[lastUserMsgIndex],
                detectedLanguage: data.detectedLanguage
              };
            }
            return updatedMsgs;
          });
        }
        
        // 先添加空的AI消息
        setMessages(msgs => {
          const newMsgs = [...msgs, { 
            role: 'ai', 
            content: '',
            model: data.model,
            responseType: data.responseType
          }];
          
          // 使用打字机效果显示内容
          setTimeout(() => {
            typewriterEffect(responseContent, newMsgs.length - 1);
          }, 100);
          
          return newMsgs;
        });

        // 清除图片
        setSelectedImage(null);
        setImagePreview(null);
        if (fileInputRef.current) {
          fileInputRef.current.value = '';
        }

        // 实时更新会话列表（发送消息不影响最近7天统计，因为基于创建时间）
        await loadSessions();
        
      } else {
        // AI 返回错误
        setMessages(msgs => [...msgs, { 
          role: 'ai', 
          content: `错误: ${data.error} - ${data.message || 'AI无响应'}`,
          isError: true
        }]);
      }
    } catch (e) {
      setMessages(msgs => [...msgs, { 
        role: 'ai', 
        content: '网络错误或服务器无响应',
        isError: true
      }]);
    }
    setLoading(false);
    setTimeout(scrollToBottom, 100);
  };

  // 回车发送
  const handleKeyDown = e => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  // 开始/停止语音录制
  const toggleVoiceRecording = () => {
    if (!recognition) {
      alert('浏览器不支持语音识别功能');
      return;
    }
    
    if (isRecording) {
      recognition.stop();
    } else {
      // 清空之前的输入
      setInput('');
      // 重新设置语言
      recognition.lang = voiceLanguage;
      
      // 添加延迟确保设置生效
      setTimeout(() => {
        try {
          recognition.start();
          console.log('开始语音识别，语言:', voiceLanguage);
        } catch (error) {
          console.error('启动语音识别失败:', error);
          setVoiceStatus('启动失败');
        }
      }, 100);
    }
  };

  // 测试语音识别
  const testVoiceRecognition = () => {
    if (!recognition) {
      alert('浏览器不支持语音识别功能');
      return;
    }
    
    console.log('=== 语音识别诊断信息 ===');
    console.log('当前语言设置:', voiceLanguage);
    console.log('浏览器支持:', 'webkitSpeechRecognition' in window ? 'webkitSpeechRecognition' : 'SpeechRecognition');
    console.log('用户代理:', navigator.userAgent);
    console.log('HTTPS状态:', window.location.protocol === 'https:' ? '安全连接' : '非安全连接');
    
    // 测试网络连接
    console.log('🌐 测试网络连接...');
    fetch('https://www.google.com/favicon.ico', { mode: 'no-cors' })
      .then(() => {
        console.log('✅ 网络连接正常');
      })
      .catch(() => {
        console.warn('⚠️ 网络连接可能有问题');
      });
    
    // 检查麦克风权限
    navigator.mediaDevices.getUserMedia({ audio: true })
      .then(stream => {
        console.log('✅ 麦克风权限已获取');
        console.log('音频轨道:', stream.getAudioTracks().map(track => track.label));
        stream.getTracks().forEach(track => track.stop());
        
        // 清空输入并开始语音识别测试
        setInput('');
        recognition.lang = voiceLanguage;
        
        setTimeout(() => {
          try {
            recognition.start();
            console.log('🎤 开始语音识别测试，请说话...');
            setVoiceStatus('测试中...');
          } catch (error) {
            console.error('启动语音识别测试失败:', error);
            setVoiceStatus('测试失败');
          }
        }, 100);
      })
      .catch(err => {
        console.error('❌ 麦克风权限错误:', err);
        let errorMsg = '无法访问麦克风\n\n';
        switch (err.name) {
          case 'NotAllowedError':
            errorMsg += '请允许浏览器使用麦克风权限，然后刷新页面重试';
            break;
          case 'NotFoundError':
            errorMsg += '未找到麦克风设备，请检查设备连接';
            break;
          case 'NotReadableError':
            errorMsg += '麦克风被其他应用占用，请关闭其他使用麦克风的应用';
            break;
          default:
            errorMsg += `错误类型: ${err.name}\n错误信息: ${err.message}`;
        }
        alert(errorMsg);
      });
  };

  // 图片压缩函数
  const compressImage = (file, maxWidth = 1024, quality = 0.8) => {
    return new Promise((resolve) => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      const img = new Image();
      
      img.onload = () => {
        // 计算新的尺寸，保持宽高比
        let { width, height } = img;
        if (width > maxWidth) {
          height = (height * maxWidth) / width;
          width = maxWidth;
        }
        
        canvas.width = width;
        canvas.height = height;
        
        // 绘制压缩后的图片
        ctx.drawImage(img, 0, 0, width, height);
        
        // 转换为base64，使用指定的质量
        const compressedDataUrl = canvas.toDataURL('image/jpeg', quality);
        resolve(compressedDataUrl);
      };
      
      img.src = URL.createObjectURL(file);
    });
  };

  // 图片处理函数
  const handleImageUpload = async (event) => {
    const file = event.target.files[0];
    if (file) {
      if (file.size > 20 * 1024 * 1024) { // 20MB限制
        alert('图片大小不能超过20MB');
        return;
      }
      
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件');
        return;
      }
      
      try {
        // 压缩图片
        const compressedImage = await compressImage(file);
        setSelectedImage(compressedImage);
        setImagePreview(compressedImage);
        
        // 显示压缩信息
        const originalSize = (file.size / 1024 / 1024).toFixed(2);
        const compressedSize = (compressedImage.length * 0.75 / 1024 / 1024).toFixed(2);
        console.log(`图片压缩: ${originalSize}MB -> ${compressedSize}MB`);
      } catch (error) {
        console.error('图片压缩失败:', error);
        // 如果压缩失败，使用原始图片
        const reader = new FileReader();
        reader.onload = (e) => {
          setSelectedImage(e.target.result);
          setImagePreview(e.target.result);
        };
        reader.readAsDataURL(file);
      }
    }
  };

  const removeImage = () => {
    setSelectedImage(null);
    setImagePreview(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleDragOver = (e) => {
    e.preventDefault();
  };

  const handleDrop = async (e) => {
    e.preventDefault();
    const files = e.dataTransfer.files;
    if (files.length > 0) {
      const file = files[0];
      if (file.type.startsWith('image/')) {
        if (file.size > 20 * 1024 * 1024) {
          alert('图片大小不能超过20MB');
          return;
        }
        
        try {
          // 压缩图片
          const compressedImage = await compressImage(file);
          setSelectedImage(compressedImage);
          setImagePreview(compressedImage);
          
          // 显示压缩信息
          const originalSize = (file.size / 1024 / 1024).toFixed(2);
          const compressedSize = (compressedImage.length * 0.75 / 1024 / 1024).toFixed(2);
          console.log(`图片压缩: ${originalSize}MB -> ${compressedSize}MB`);
        } catch (error) {
          console.error('图片压缩失败:', error);
          // 如果压缩失败，使用原始图片
          const reader = new FileReader();
          reader.onload = (e) => {
            setSelectedImage(e.target.result);
            setImagePreview(e.target.result);
          };
          reader.readAsDataURL(file);
        }
      } else {
        alert('请拖拽图片文件');
      }
    }
  };

  // 加载聊天统计信息
  const loadChatStats = async () => {
    try {
      const response = await fetch('/zjx/chat-stats?userId=anonymous');
      const data = await response.json();
      if (data.success) {
        setChatStats(data.stats);
      }
    } catch (error) {
      console.error('加载聊天统计失败:', error);
    }
  };

  // 导出聊天记录
  const exportChatSession = async (sessionId) => {
    try {
      const response = await fetch(`/zjx/sessions/${sessionId}/export`);
      const data = await response.json();
      
      // 检查是否有错误
      if (data.error) {
        alert('导出失败: ' + data.message);
        return;
      }
      
      // 检查是否有导出数据
      if (data.sessionId) {
        // 创建并下载文件
        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `chat-session-${sessionId}-${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        console.log('导出成功，文件已下载');
      } else {
        alert('导出失败: 未获取到有效的会话数据');
      }
    } catch (error) {
      console.error('导出聊天记录失败:', error);
      alert('导出失败: ' + error.message);
    }
  };

  return (
    <div style={{ maxWidth: 800, margin: '40px auto', background: '#fff', borderRadius: 12, boxShadow: '0 4px 24px #0001', padding: 24 }}>
      <style>
        {`
          @keyframes dotBounce {
            0%, 60%, 100% {
              transform: translateY(0);
              opacity: 1;
            }
            30% {
              transform: translateY(-4px);
              opacity: 0.8;
            }
          }
        `}
      </style>
             <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
         <h2 style={{ margin: 0 }}>AI 对话</h2>
         <div style={{ display: 'flex', gap: 8 }}>
           <button
             onClick={() => setShowSessions(!showSessions)}
             style={{
               padding: '8px 16px',
               borderRadius: 6,
               background: '#6c757d',
               color: 'white',
               border: 'none',
               cursor: 'pointer',
               fontSize: 14
             }}
           >
             💾 历史对话
           </button>
           <button
             onClick={createNewSession}
             style={{
               padding: '8px 16px',
               borderRadius: 6,
               background: '#28a745',
               color: 'white',
               border: 'none',
               cursor: 'pointer',
               fontSize: 14
             }}
           >
             ➕ 新对话
           </button>
         </div>
       </div>
      
      {/* 模型选择和控制面板 */}
      <div style={{ 
        border: '1px solid #ddd', 
        borderRadius: 8, 
        padding: 16, 
        marginBottom: 16,
        backgroundColor: '#f8f9fa'
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
          <h3 style={{ margin: 0 }}>模型配置</h3>
          <div style={{ display: 'flex', gap: 8 }}>
            <button
              onClick={checkOllamaStatus}
              style={{
                padding: '6px 12px',
                backgroundColor: '#28a745',
                color: 'white',
                border: 'none',
                borderRadius: 4,
                cursor: 'pointer',
                fontSize: 12
              }}
            >
              检查Ollama
            </button>
          </div>
        </div>
        
        {/* 模型选择 */}
        <div style={{ display: 'flex', gap: 16, marginBottom: 12 }}>
          <div>
            <label style={{ display: 'block', marginBottom: 4, fontSize: 14 }}>选择模型:</label>
            <select
              value={selectedModel}
              onChange={(e) => setSelectedModel(e.target.value)}
              style={{
                padding: '6px 12px',
                borderRadius: 4,
                border: '1px solid #ddd',
                fontSize: 14
              }}
            >
              <option value="ollama">Ollama (本地)</option>
            </select>
          </div>
          
          {/* 模型状态显示 */}
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 12, color: '#666' }}>
              <span style={{ color: ollamaStatus?.success ? '#28a745' : '#dc3545' }}>
                Ollama 状态: {ollamaStatus?.success ? '正常' : '异常'}
                {ollamaStatus?.modelConfigured && ` (${ollamaStatus.modelConfigured})`}
              </span>
            </div>
          </div>
        </div>

        {/* 参数配置 */}
          <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
            <div style={{ flex: 1, minWidth: 200 }}>
              <label style={{ display: 'block', marginBottom: 4, fontSize: 14 }}>系统提示词:</label>
              <textarea
                value={systemPrompt}
                onChange={(e) => setSystemPrompt(e.target.value)}
                style={{
                  width: '100%',
                  height: 60,
                  padding: '6px 8px',
                  borderRadius: 4,
                  border: '1px solid #ddd',
                  fontSize: 12,
                  resize: 'vertical'
                }}
                placeholder="设置系统提示词..."
              />
            </div>
            <div style={{ minWidth: 150 }}>
              <label style={{ display: 'block', marginBottom: 4, fontSize: 14 }}>
                温度: {temperature}
              </label>
              <input
                type="range"
                min="0"
                max="2"
                step="0.1"
                value={temperature}
                onChange={(e) => setTemperature(parseFloat(e.target.value))}
                style={{ width: '100%' }}
              />
            </div>
            <div style={{ minWidth: 150 }}>
              <label style={{ display: 'block', marginBottom: 4, fontSize: 14 }}>
                最大令牌: {maxTokens}
              </label>
              <input
                type="range"
                min="100"
                max="4096"
                step="100"
                value={maxTokens}
                onChange={(e) => setMaxTokens(parseInt(e.target.value))}
                style={{ width: '100%' }}
              />
            </div>
          </div>
       </div>

       {/* 聊天统计信息 */}
       {showStats && chatStats && (
         <div style={{ 
           border: '1px solid #ddd', 
           borderRadius: 8, 
           padding: 16, 
           marginBottom: 16,
           backgroundColor: '#e8f5e8'
         }}>
           <h3 style={{ margin: '0 0 12px 0', fontSize: 16, color: '#2e7d32' }}>
             📊 聊天统计
           </h3>
           <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 12 }}>
             <div style={{ textAlign: 'center', padding: '8px', backgroundColor: '#fff', borderRadius: 4 }}>
               <div style={{ fontSize: 20, fontWeight: 'bold', color: '#2e7d32' }}>{chatStats.totalSessions}</div>
               <div style={{ fontSize: 12, color: '#666' }}>总会话数</div>
             </div>
             <div style={{ textAlign: 'center', padding: '8px', backgroundColor: '#fff', borderRadius: 4 }}>
               <div style={{ fontSize: 20, fontWeight: 'bold', color: '#1976d2' }}>{chatStats.totalMessages}</div>
               <div style={{ fontSize: 12, color: '#666' }}>总消息数</div>
             </div>
             <div style={{ textAlign: 'center', padding: '8px', backgroundColor: '#fff', borderRadius: 4 }}>
               <div style={{ fontSize: 20, fontWeight: 'bold', color: '#f57c00' }}>{chatStats.recentSessions}</div>
               <div style={{ fontSize: 12, color: '#666' }}>最近7天</div>
             </div>
           </div>
           {chatStats.modelStats && chatStats.modelStats.length > 0 && (
             <div style={{ marginTop: 12, fontSize: 12, color: '#666' }}>
               <strong>常用模型:</strong> {chatStats.modelStats.map(stat => `${stat.model}(${stat.count})`).join(', ')}
             </div>
           )}
         </div>
       )}

       {/* 会话列表 */}
       {showSessions && (
         <div style={{ 
           border: '1px solid #ddd', 
           borderRadius: 8, 
           padding: 16, 
           marginBottom: 16,
           backgroundColor: '#f8f9fa',
           maxHeight: 300,
           overflowY: 'auto'
         }}>
           <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
             <h3 style={{ margin: 0, fontSize: 16 }}>
               历史对话
                           {sessionsLoading && (
              <span style={{ fontSize: 12, color: '#007bff', marginLeft: 8 }}>
                🔄 更新中
                <span style={{ display: 'inline-block' }}>
                  <span style={{ 
                    display: 'inline-block',
                    animation: 'dotBounce 1.4s infinite',
                    animationDelay: '0s'
                  }}>.</span>
                  <span style={{ 
                    display: 'inline-block',
                    animation: 'dotBounce 1.4s infinite',
                    animationDelay: '0.2s'
                  }}>.</span>
                  <span style={{ 
                    display: 'inline-block',
                    animation: 'dotBounce 1.4s infinite',
                    animationDelay: '0.4s'
                  }}>.</span>
                </span>
              </span>
            )}
             </h3>
             <button
               onClick={() => setShowStats(!showStats)}
               style={{
                 padding: '4px 8px',
                 backgroundColor: '#28a745',
                 color: 'white',
                 border: 'none',
                 borderRadius: 4,
                 cursor: 'pointer',
                 fontSize: 12
               }}
             >
               {showStats ? '隐藏统计' : '显示统计'}
             </button>
           </div>
            {sessionsLoading ? (
              <div style={{ textAlign: 'center', color: '#666', padding: '20px' }}>
                🔄 正在更新会话列表...
              </div>
            ) : sessions.length === 0 ? (
              <div style={{ textAlign: 'center', color: '#666', padding: '20px' }}>
                暂无历史对话
              </div>
            ) : (
             <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
               {sessions.map((session) => (
                 <div key={session.sessionId} style={{
                   display: 'flex',
                   justifyContent: 'space-between',
                   alignItems: 'center',
                   padding: '8px 12px',
                   border: '1px solid #ddd',
                   borderRadius: 6,
                   backgroundColor: currentSessionId === session.sessionId ? '#e3f2fd' : '#fff'
                 }}>
                   <div style={{ flex: 1, cursor: 'pointer' }} onClick={() => loadSession(session.sessionId)}>
                     <div style={{ fontWeight: 'bold', fontSize: 14 }}>{session.title}</div>
                     <div style={{ fontSize: 12, color: '#666' }}>
                       {new Date(session.updatedAt).toLocaleString()} · {session.messageCount} 条消息
                     </div>
                   </div>
                   <div style={{ display: 'flex', gap: 4 }}>
                     <button
                       onClick={() => exportChatSession(session.sessionId)}
                       style={{
                         padding: '4px 8px',
                         borderRadius: 4,
                         background: '#17a2b8',
                         color: 'white',
                         border: 'none',
                         cursor: 'pointer',
                         fontSize: 12
                       }}
                       title="导出聊天记录"
                     >
                       导出
                     </button>
                     <button
                       onClick={() => deleteSession(session.sessionId)}
                       style={{
                         padding: '4px 8px',
                         borderRadius: 4,
                         background: '#dc3545',
                         color: 'white',
                         border: 'none',
                         cursor: 'pointer',
                         fontSize: 12
                       }}
                     >
                       删除
                     </button>
                   </div>
                 </div>
               ))}
             </div>
           )}
         </div>
       )}
       
               {/* 图片预览区域 */}
        {imagePreview && (
          <div style={{ 
            border: '1px solid #ddd', 
            borderRadius: 8, 
            padding: 16, 
            marginBottom: 16,
            backgroundColor: '#f8f9fa'
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
              <h4 style={{ margin: 0, fontSize: 14 }}>📷 图片预览</h4>
              <button
                onClick={removeImage}
                style={{
                  padding: '4px 8px',
                  borderRadius: 4,
                  background: '#dc3545',
                  color: 'white',
                  border: 'none',
                  cursor: 'pointer',
                  fontSize: 12
                }}
              >
                删除图片
              </button>
            </div>
            <div style={{ textAlign: 'center' }}>
              <img 
                src={imagePreview} 
                alt="预览" 
                style={{ 
                  maxWidth: '100%', 
                  maxHeight: 200, 
                  borderRadius: 8,
                  border: '1px solid #ddd'
                }} 
              />
            </div>
          </div>
        )}

        <div 
          ref={chatRef} 
          style={{ 
            height: 400, 
            overflowY: 'auto', 
            background: '#f7f7fa', 
            borderRadius: 8, 
            padding: 12, 
            marginBottom: 16 
          }}
        >
                 {messages.map((msg, i) => (
           <div key={i} style={{ display: 'flex', flexDirection: msg.role === 'user' ? 'row-reverse' : 'row', alignItems: 'flex-start', margin: '8px 0' }}>
             <div style={{
               width: 36, height: 36, borderRadius: '50%', 
               background: msg.role === 'user' ? 'linear-gradient(135deg,#667eea,#764ba2)' : '#eee',
               display: 'flex', alignItems: 'center', justifyContent: 'center', 
               fontSize: 22, margin: '0 8px', flexShrink: 0
             }}>
               {msg.role === 'user' ? '🧑' : '🤖'}
             </div>
             <div style={{ maxWidth: '70%' }}>
               {msg.image && (
                 <div style={{ marginBottom: 8 }}>
                   <img 
                     src={msg.image} 
                     alt="用户上传的图片" 
                     style={{ 
                       maxWidth: '100%', 
                       maxHeight: 200, 
                       borderRadius: 8,
                       border: '1px solid #ddd'
                     }} 
                   />
                 </div>
               )}
               {msg.content && (
                 <div>
                   <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                     <span style={{
                       display: 'inline-block',
                       background: msg.isError ? '#f8d7da' : (msg.role === 'user' ? 'linear-gradient(90deg,#667eea,#764ba2)' : '#fff'),
                       color: msg.isError ? '#721c24' : (msg.role === 'user' ? '#fff' : '#333'),
                       borderRadius: 16,
                       padding: '8px 16px',
                       boxShadow: msg.role === 'user' ? '0 2px 8px #667eea22' : '0 2px 8px #0001',
                       wordBreak: 'break-all'
                     }}>{msg.content}</span>
                     {msg.role === 'user' && msg.detectedLanguage && (
                       <span style={{
                         fontSize: 10,
                         padding: '2px 6px',
                         borderRadius: 8,
                         background: '#17a2b8',
                         color: '#fff',
                         whiteSpace: 'nowrap'
                       }}>
                         🌍 {msg.detectedLanguage.languageName}
                       </span>
                     )}
                   </div>
                   {msg.model && (
                     <div style={{ fontSize: 10, color: '#666', marginTop: 4 }}>
                       模型: Ollama
                     </div>
                   )}
                 </div>
               )}
             </div>
           </div>
         ))}
        {loading && (
          <div style={{ color: '#aaa', fontStyle: 'italic', margin: '8px 0', display: 'flex', alignItems: 'center' }}>
            <div style={{width:36,height:36,borderRadius:'50%',background:'#eee',display:'flex',alignItems:'center',justifyContent:'center',fontSize:22,margin:'0 8px'}}>🤖</div>
            AI 正在分析... (Ollama)
          </div>
        )}
      </div>

      

                          <div 
         style={{ display: 'flex', gap: 8, alignItems: 'flex-end' }}
         onDragOver={handleDragOver}
         onDrop={handleDrop}
       >
         <div style={{ flex: 1 }}>
           <input
             type="text"
             value={input}
             onChange={e => setInput(e.target.value)}
             onKeyDown={handleKeyDown}
             placeholder="请输入你的问题或拖拽图片到此处..."
             style={{ 
               width: '100%',
               padding: '10px 16px', 
               borderRadius: 20, 
               border: '1px solid #ddd', 
               outline: 'none', 
               fontSize: 16 
             }}
             disabled={loading}
           />
         </div>
         <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
           {/* 图片上传按钮 */}
           <input
             type="file"
             ref={fileInputRef}
             onChange={handleImageUpload}
             accept="image/*"
             style={{ display: 'none' }}
           />
           <button
             onClick={() => fileInputRef.current?.click()}
             disabled={loading}
             style={{ 
               padding: '10px 16px', 
               borderRadius: 20, 
               background: '#28a745', 
               color: '#fff', 
               border: 'none', 
               fontSize: 16, 
               cursor: loading ? 'not-allowed' : 'pointer',
               display: 'flex',
               alignItems: 'center',
               gap: '4px'
             }}
             title="上传图片"
           >
             📷 图片
           </button>
           
           <select
             value={voiceLanguage}
             onChange={(e) => setVoiceLanguage(e.target.value)}
             style={{
               padding: '6px 8px',
               borderRadius: 12,
               border: '1px solid #ddd',
               fontSize: 12,
               background: '#fff'
             }}
             disabled={isRecording}
           >
             <option value="zh-CN">中文</option>
             <option value="en-US">English</option>
             <option value="ja-JP">日本語</option>
             <option value="ko-KR">한국어</option>
           </select>
           <button
             onClick={toggleVoiceRecording}
             disabled={loading || isRecording}
             style={{ 
               padding: '10px 16px', 
               borderRadius: 20, 
               background: isRecording ? '#dc3545' : '#6c757d', 
               color: '#fff', 
               border: 'none', 
               fontSize: 16, 
               cursor: (loading || isRecording) ? 'not-allowed' : 'pointer',
               display: 'flex',
               alignItems: 'center',
               gap: '4px'
             }}
             title={isRecording ? '停止录音' : '语音输入'}
           >
             {isRecording ? '🔴' : '🎤'}
             {isRecording ? '录音中...' : '语音'}
           </button>
           <button
             onClick={testVoiceRecognition}
             disabled={loading || isRecording}
             style={{ 
               padding: '8px 12px', 
               borderRadius: 12, 
               background: '#17a2b8', 
               color: '#fff', 
               border: 'none', 
               fontSize: 12, 
               cursor: (loading || isRecording) ? 'not-allowed' : 'pointer'
             }}
             title="测试语音识别"
           >
             🧪 测试
           </button>
         </div>
         <button
           onClick={sendMessage}
           disabled={loading || (!input.trim() && !selectedImage)}
           style={{ 
             padding: '10px 24px', 
             borderRadius: 20, 
             background: 'linear-gradient(90deg,#667eea,#764ba2)', 
             color: '#fff', 
             border: 'none', 
             fontSize: 16, 
             cursor: loading ? 'not-allowed' : 'pointer' 
           }}
         >
           发送
         </button>
       </div>
      
                   <div style={{ textAlign: 'center', marginTop: 12, fontSize: 12, color: '#666' }}>
        当前模型: Ollama (本地)
        {isRecording && (
          <span style={{ color: '#dc3545', marginLeft: 8 }}>
            🎤 正在录音，请说话...
          </span>
        )}
        <br />
        <span style={{ fontSize: 11, color: '#17a2b8' }}>
          语音状态: {voiceStatus}
          {retryCount > 0 && (
            <span style={{ color: '#ffc107', marginLeft: 4 }}>
              (重试 {retryCount}/3)
            </span>
          )}
        </span>
      </div>
      {!recognition && (
        <div style={{ textAlign: 'center', marginTop: 8, fontSize: 11, color: '#ff6b6b', backgroundColor: '#fff5f5', padding: '8px', borderRadius: '6px' }}>
          ⚠️ 浏览器不支持语音识别功能，请使用Chrome、Edge或Safari浏览器
        </div>
      )}
             {recognition && (
         <div style={{ textAlign: 'center', marginTop: 8, fontSize: 11, color: '#28a745', backgroundColor: '#f8fff9', padding: '8px', borderRadius: '6px' }}>
           💡 语音使用提示：点击🎤按钮开始录音，说话完成后会自动停止并转换为文字
           <br />
           📝 使用建议：说话清晰，避免噪音，录音最长10秒
           <br />
           🌐 网络错误时系统会自动重试，最多3次
           <br />
           🔧 如果遇到问题，请点击🧪测试按钮进行诊断，或检查浏览器控制台的错误信息
         </div>
       )}
       
                    <div style={{ textAlign: 'center', marginTop: 8, fontSize: 11, color: '#17a2b8', backgroundColor: '#f0f8ff', padding: '8px', borderRadius: '6px' }}>
               📷 图片识别功能：点击📷按钮上传图片，或直接拖拽图片到输入框
               <br />
               💡 支持格式：JPG、PNG、GIF等，最大20MB（自动压缩）
               <br />
               🤖 AI将自动识别图片内容并回答相关问题
               <br />
               🌍 智能语言匹配：AI会根据您发送的语言自动回复相同语言
               <br />
               💾 聊天记录自动保存：所有对话都会自动保存到数据库，支持导出和统计
             </div>
    </div>
  );
}
